package top.wshape1.largefileupload.config;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.errors.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @author Wshape1
 * @version 1.0
 * @description
 * @since 2025-01-24
 */

@EnableConfigurationProperties(MinioProperty.class)
@Configuration
@Slf4j
public class MinioConfig {

    @Bean
    public MinioClient minioClient(MinioProperty minioProperty) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        MinioClient client = MinioClient.builder()
                .endpoint(minioProperty.getEndpoint())
                .credentials(minioProperty.getAccessKey(), minioProperty.getSecretKey())
                .build();

        boolean bucketExist = client.bucketExists(BucketExistsArgs.builder().bucket(minioProperty.getBucketName()).build());

        if (!bucketExist) {
            client.makeBucket(MakeBucketArgs.builder().bucket(minioProperty.getBucketName()).build());
            log.info("bucket:{} not exist, create it.", minioProperty.getBucketName());
        } else {
            log.info("bucket:{} exist.", minioProperty.getBucketName());
        }

        return client;
    }

}
